package com.demo.dao.impl;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.demo.bean.User;
import com.demo.dao.IUserDao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserDaoImpl implements IUserDao {

	@Autowired
	private final DataSource dataSource = new ComboPooledDataSource("remote");
	
	@Override
	public User queryByName(String name) {
		QueryRunner query = new QueryRunner(dataSource);
		User user = null;
		String sql = "SELECT * FROM user WHERE username = ?";
		try {
			user = query.query(sql, 
					new BeanHandler<User>(User.class), 
					name);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return user;
	}

	@Override
	public User queryById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean add(User user) {
		QueryRunner query = new QueryRunner(dataSource);
		String sql = "INSERT INTO user (username, password, email) VALUES (?, ?, ?)";
		try {
			query.insert(sql, 
					new BeanHandler<User>(User.class), 
					user.getUsername(), 
					user.getPassword(),
					user.getEmail());
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
